package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.HouseQaStatus;
import com.wzdigit.wms.raw.domain.dto.IfAsnHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfAsnDtl;
import com.wzdigit.wms.raw.domain.mid.IfAsnHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfAsnDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfAsnHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-送货单 同步 收货单
 * </p>
 *
 * @author chao shuai
 * @since 2021-03-16
 */
@Service
public class IfAsnHeaderService {

    @Autowired
    private IfAsnHeaderMapper ifAsnHeaderMapper;

    @Autowired
    private IfAsnDtlMapper ifAsnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;
    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    CodeMappingService codeMappingService;
    @Autowired
    MappingHouseService mappingHouseService;

    @Autowired
    WarehouseMapper warehouseMapper;

    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    private final String syncType = SyncTypeConstant.IF_ASN_TO_ASN;

    public List<IfAsnHeaderDto> selectSyncData() {
        ArrayList<IfAsnHeaderDto> ifAsnHeaderDtos = new ArrayList<>();
        QueryWrapper<IfAsnHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfAsnHeader> selectSyncData = ifAsnHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfAsnHeader ifAsnHeader : selectSyncData) {
                IfAsnHeaderDto ifAsnHeaderDto = new IfAsnHeaderDto();
                BeanUtil.copyNonNull(ifAsnHeader, ifAsnHeaderDto);
                List<IfAsnDtl> ifSalesreturnDtls = ifAsnDtlMapper.selectList(new QueryWrapper<>(
                        new IfAsnDtl().setIfAsnHeaderId(ifAsnHeader.getIfAsnHeaderId())
                ));
                ifAsnHeaderDto.setIfAsnDtlList(ifSalesreturnDtls);
                ifAsnHeaderDtos.add(ifAsnHeaderDto);
            }

        }
        return ifAsnHeaderDtos;
    }



    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncData(IfAsnHeaderDto data, boolean isSyncError) throws Exception {
        String asnNumber = data.getAsnNumber(); //送货单号
        List<IfAsnDtl> ifAsnDtlList = data.getIfAsnDtlList();
        AsnHeader asnHeader = new AsnHeader();
        //同步主表信息
        VendorDTO vendor = basicVendorApi.getVendorByCode(data.getVendorCode());
        if (vendor == null) {
            throw new SyncException(syncType, asnNumber, "供应商" + data.getVendorCode() + "不存在");
        }
        asnHeader.setAsnNo(data.getAsnNumber());
        asnHeader.setFactory(data.getFactoryCode());//工厂
        asnHeader.setMfgPlant(data.getBranch());    //分厂
        asnHeader.setVendorId(vendor.getVendorId()); //供应商
        asnHeader.setAsnRef1(data.getStorageCode());         //ASN参考信息1
        asnHeader.setPlaceOfDelivery(data.getStorageName());  //交货地
        asnHeader.setJitFlag(data.getJitFlag());       //JIT属性
        asnHeader.setStatus(data.getStatus()==null?null:Integer.valueOf(data.getStatus()));  //状态
        asnHeader.setComments(data.getHeaderRemarks());   //备注
        asnHeader.setAsnType(AsnTypeEnum.R14.code);//采购入库
        asnHeader.setReleaseStatus(1);
        asnHeader.setAsnCreateUser(data.getCreateUser());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        asnHeader.setQcStatus( QcStatusEnum.未创建质检单.getCode());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));

        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(asnNumber)));
        if (asnHeaderRecord == null) {
            asnHeader.setCreateTime(new Date());
            asnHeader.setStatus( AsnHeaderStatusEnum.CREATE.getCode());//新建状态

            asnHeader.setCreateTime(data.getCreateTime());
            asnHeader.setCreateUser(data.getCreateUser());

            asnHeaderMapper.insert(asnHeader);
        } else {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeader.setAsnNo(asnHeaderRecord.getAsnNo());
            asnHeaderMapper.updateById(asnHeader);
        }

        for (IfAsnDtl ifAsnDtl : ifAsnDtlList) {
            //查询SKUID ；
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifAsnDtl.getItemCode());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, asnNumber, "物料编码" + ifAsnDtl.getItemCode() + "不存在");
            }
            //获取仓库
            if(ifAsnDtl.getReceivingWarehouseCode() == null){
                throw new SyncException(syncType, asnNumber, "SAP仓库编码" + ifAsnDtl.getReceivingWarehouseCode() + "为空");
            }
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(ifAsnDtl.getReceivingWarehouseCode());
            if(houseQaStatus==null){
                throw new SyncException(syncType, asnNumber, "SAP仓库编码" + ifAsnDtl.getReceivingWarehouseCode() + "无法转换成WMS仓库");
            }


            AsnDtl asnDtl = new AsnDtl();

            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setAsnNo(ifAsnDtl.getAsnNumber());
            asnDtl.setAsnLineNo(ifAsnDtl.getAsnLineNum());
            asnDtl.setPoNo(ifAsnDtl.getSegment1());
            asnDtl.setPoLineNo(ifAsnDtl.getLineNum());
            asnDtl.setSourceNo(ifAsnDtl.getDocumentNumber());
            asnDtl.setMfgLine(ifAsnDtl.getLineCode());
            asnDtl.setCallTime(ifAsnDtl.getCallTime());
            asnDtl.setSkuId(sku.getSkuId());//查询SKU
            asnDtl.setSkuDesc(ifAsnDtl.getItemDescription());
            asnDtl.setUnit(ifAsnDtl.getUomCode());
            asnDtl.setWhsId(houseQaStatus.getWhsId());
            asnDtl.setOrderQty(ifAsnDtl.getQuantity());
            asnDtl.setOrderQtyEa(ifAsnDtl.getQuantity());
            asnDtl.setComments(ifAsnDtl.getRemarks());
            asnDtl.setDoNo(ifAsnDtl.getOrderNumber());
            asnDtl.setQcStatus(QcStatusEnum.未创建质检单.getCode());
            asnDtl.setQaStatus(QaStatusEnum.WAIT.code);


            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnNo(asnHeader.getAsnNo()).setAsnLineNo(ifAsnDtl.getAsnLineNum())));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setStatus( AsnDtlStatusEnum.CREATE.getCode());//新建状态

                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, asnNumber, e.getMessage());
                }
            }
            int row = ifAsnHeaderMapper.updateFlagById(data.getIfAsnHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, asnNumber);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, asnNumber);
            }
        }

    }


}
